package com.qo.qsdk.ui.base;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qo.qsdk.utils.DynamicUtils;
import com.qo.qsdk.utils.Language;

public class DragViewLayout extends RelativeLayout {

    private static final String TAG = DragViewLayout.class.getSimpleName();

    //view所在位置
    int mLastX, mLastY;

    //屏幕高宽
    int mScreenWidth, mScreenHeight;

    //view高宽
    int mWidth, mHeight;

    /**
     * 是否在拖拽过程中
     */
    boolean isDrag = false;

    /**
     * 系统最小滑动距离
     * @param context
     */
    int mTouchSlop = 0;

    WindowManager.LayoutParams floatLayoutParams;
    WindowManager mWindowManager;

    //手指触摸位置
    private float xInScreen;
    private float yInScreen;
    private float xInView;
    public float yInView;
    private View mMain, mMainR;
    private LayoutInflater mInflater;
    private Context mContext;
    public View mLogo, mPay, mCustomer, mClose;
    private TextView mPayT, mCustomerT, mCloseT;
    public View mLogoR, mPayR, mCustomerR, mCloseR;
    private TextView mPayTR, mCustomerTR, mCloseTR;
    public boolean isOpen;

    public interface FloatListener {
        void onPay();
        void onCustomer();
        void onClose();
    }

    Float.FloatListener floatListener;

    public void setFloatListener(Float.FloatListener floatListener) {
        this.floatListener = floatListener;
    }

    public DragViewLayout(Context context) {
        this(context, null);
    }

    public DragViewLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DragViewLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;

        floatLayoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.FIRST_SUB_WINDOW,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                        | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                PixelFormat.RGBA_8888);

        mScreenWidth = context.getResources().getDisplayMetrics().widthPixels;
        mScreenHeight = context.getResources().getDisplayMetrics().heightPixels;
//        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        mWindowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        mInflater = LayoutInflater.from(context);
        mMainR = mInflater.inflate(DynamicUtils.layout(context, "qsdk_f_r"), null);
        mMain = mInflater.inflate(DynamicUtils.layout(context, "qsdk_f_l"), null);
        init(mMain);
    }

    private void init(View v) {
        mPay = v.findViewById(DynamicUtils.id(mContext, "pay"));
        mLogo = v.findViewById(DynamicUtils.id(mContext, "logo"));
        mCustomer = v.findViewById(DynamicUtils.id(mContext, "customer"));
        mClose = v.findViewById(DynamicUtils.id(mContext, "close"));
        mPayT = v.findViewById(DynamicUtils.id(mContext, "payT"));
        mCustomerT = v.findViewById(DynamicUtils.id(mContext, "customerT"));
        mCloseT = v.findViewById(DynamicUtils.id(mContext, "closeT"));

        mPayR = mMainR.findViewById(DynamicUtils.id(mContext, "payR"));
        mLogoR = mMainR.findViewById(DynamicUtils.id(mContext, "logoR"));
        mCustomerR = mMainR.findViewById(DynamicUtils.id(mContext, "customerR"));
        mCloseR = mMainR.findViewById(DynamicUtils.id(mContext, "closeR"));
        mPayTR = mMainR.findViewById(DynamicUtils.id(mContext, "payTR"));
        mCustomerTR = mMainR.findViewById(DynamicUtils.id(mContext, "customerTR"));
        mCloseTR = mMainR.findViewById(DynamicUtils.id(mContext, "closeTR"));

        refresh();
        mLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        addView(mMain, mLayoutParams);
        closeMenu(mContext);
    }

    LayoutParams mLayoutParams;

    public void refresh() {
        mPayT.setText(Language.Float_Pay.toString());
        mCustomerT.setText(Language.Float_Customer.toString());
        mCloseT.setText(Language.Float_Hide.toString());

        mPayTR.setText(Language.Float_Pay.toString());
        mCustomerTR.setText(Language.Float_Customer.toString());
        mCloseTR.setText(Language.Float_Hide.toString());
    }

    public void toggleMenu(Context activity) {
        if (isOpen) closeMenu(activity);
        else openMenu(activity);
    }

    public void openMenu(Context activity) {
        show(activity, true, true, true);
        isOpen = true;

//        int x = (int) (xInScreen - xInView);
//        int y = (int) (yInScreen - yInView);
//        x = isRightFloat() ? mScreenWidth - 377 : 0;
//        if(y < 0) {
//            y = 0;
//        }
//        if(y > mScreenHeight - mHeight) {
//            y = mScreenHeight - mHeight;
//        }
//        floatLayoutParams.x = x;
//        floatLayoutParams.y = y;
//        //更新位置
//        //更新位置
//        if (getParent() != null) mWindowManager.updateViewLayout(this, floatLayoutParams);
    }

    public void closeMenu(Context activity) {
        show(activity, false, false, false);
        isOpen = false;
//
//        int x = (int) (xInScreen - xInView);
//        int y = (int) (yInScreen - yInView);
//        x = isRightFloat() ? mScreenWidth - 129 : 0;
//        if(y < 0) {
//            y = 0;
//        }
//        if(y > mScreenHeight - mHeight) {
//            y = mScreenHeight - mHeight;
//        }
//        floatLayoutParams.x = x;
//        floatLayoutParams.y = y;
//        //更新位置
//        if (getParent() != null) mWindowManager.updateViewLayout(this, floatLayoutParams);
    }

    public void show(Context activity, boolean pay, boolean customer, boolean close) {
        mPay.setVisibility(pay ? View.VISIBLE : View.GONE);
        mCustomer.setVisibility(customer ? View.VISIBLE : View.GONE);
        mClose.setVisibility(close ? View.VISIBLE : View.GONE);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mLastX = (int) event.getRawX();
                mLastY = (int) event.getRawY();
                yInView = event.getY();
                xInView = event.getX();
                xInScreen = event.getRawX();
                yInScreen = event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int dx = (int) event.getRawX() - mLastX;
                int dy = (int) event.getRawY() - mLastY;
                Log.e("aa", "dx->" + dx + ",dy->" + dy + ",isDrag->" + isDrag + ",mTouchSlop->" + mTouchSlop);
                if (Math.abs(dx) >= mTouchSlop || Math.abs(dy) >= mTouchSlop) {
                    isDrag = true;
                }
                xInScreen = event.getRawX();
                yInScreen = event.getRawY();
                mLastX = (int) event.getRawX();
                mLastY = (int) event.getRawY();
                //拖拽时调用WindowManager updateViewLayout更新悬浮球位置
                updateFloatPosition(false);
                if (dragListener != null) dragListener.onMove();
                break;
            case MotionEvent.ACTION_UP:
                if (isDrag) {
                    //执行贴边
                    startAnim();
                    isDrag = false;
                }else{
                    clickFloat(event);
                }
                break;
            default:
                break;
        }
        return super.dispatchTouchEvent(event);
    }

    private void clickFloat(MotionEvent e) {
        Log.e(TAG, "clickFloat");
        float clickX = e.getRawX(), clickY = e.getRawY();

        int []location = new int[2];
        mLogo.getLocationOnScreen(location);
        float x = location[0];
        float y = location[1];
        if (clickX >= x && clickX <= x + mLogo.getWidth() && clickY >= y && clickY <= y + mLogo.getHeight()) {
            Log.e("a","logo");
            toggleMenu(mContext);
            return;
        }

        if (mPay.getVisibility() == VISIBLE) {
            Log.e("a","pay");
            mPay.getLocationOnScreen(location);
            x = location[0];
            y = location[1];
            if (clickX >= x && clickX <= x + mPay.getWidth() && clickY >= y && clickY <= y + mPay.getHeight()) {
                if (floatListener != null) floatListener.onPay();
                closeMenu(mContext);
                return;
            }
        }

        if (mCustomer.getVisibility() == VISIBLE) {
            Log.e("a","customer");
            mCustomer.getLocationOnScreen(location);
            x = location[0];
            y = location[1];
            if (clickX >= x && clickX <= x + mCustomer.getWidth() && clickY >= y && clickY <= y + mCustomer.getHeight()) {
                if (floatListener != null) floatListener.onCustomer();
                closeMenu(mContext);
                return;
            }
        }

        if (mClose.getVisibility() == VISIBLE) {
            Log.e("a","close");
            mClose.getLocationOnScreen(location);
            x = location[0];
            y = location[1];
            if (clickX >= x && clickX <= x + mClose.getWidth() && clickY >= y && clickY <= y + mClose.getHeight()) {
                if (floatListener != null) floatListener.onClose();
                closeMenu(mContext);
                hide();
                return;
            }
        }
    }

    DragListener dragListener;

    public void setDragListener(DragListener dragListener) {
        this.dragListener = dragListener;
    }

    public interface DragListener {
        void onClick(MotionEvent e);
        void onMove();
    }

    //更新悬浮球位置
    protected void updateFloatPosition(boolean isUp) {
        int x = (int) (xInScreen - xInView);
        int y = (int) (yInScreen - yInView);
        if(isUp) {
            x = isRightFloat() ? mScreenWidth - mWidth : 0;
        }
        if(y < 0) {
            y = 0;
        }
        if(y > mScreenHeight - mHeight) {
            y = mScreenHeight - mHeight;
        }
        floatLayoutParams.x = x;
        floatLayoutParams.y = y;
        //更新位置
        mWindowManager.updateViewLayout(this, floatLayoutParams);
    }

    /**
     * 是否靠右边悬浮
     * @return
     */
    boolean isRightFloat() {
        return xInScreen > mScreenWidth / 2;
    }


    //执行贴边动画
    private void startAnim(){
        ValueAnimator valueAnimator;
        if (floatLayoutParams.x < mScreenWidth / 2) {
            valueAnimator = ValueAnimator.ofInt(floatLayoutParams.x, 0);
        } else {
            valueAnimator = ValueAnimator.ofInt(floatLayoutParams.x, mScreenWidth - mWidth);
        }
        valueAnimator.setDuration(200);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                floatLayoutParams.x = (int)animation.getAnimatedValue();
                mWindowManager.updateViewLayout(DragViewLayout.this, floatLayoutParams);
            }
        });
        valueAnimator.start();
    }

    //悬浮球显示
    public void show() {
        floatLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        floatLayoutParams.x = 0;
        floatLayoutParams.y = (int)(mScreenHeight * 0.4);
        if (getParent() == null)mWindowManager.addView(this, floatLayoutParams);
    }

    public void hide() {
        if (mWindowManager != null) {
            mWindowManager.removeView(this);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (mWidth != getWidth()) {
            mWidth = getWidth();
            mHeight = getHeight();
            updateFloatPosition(true);
        }
    }
}

